package com.zhentao.file.service.impl;


import com.zhentao.file.config.MinioConfig;
import com.zhentao.file.config.MinioConfigerProperties;
import com.zhentao.file.service.FileStorageService;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@EnableConfigurationProperties(MinioConfigerProperties.class)
@Import(MinioConfig.class)
@Service
public class FileStorageServiceImpl implements FileStorageService {
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioConfigerProperties minioConfigerProperties;

    @Override
    public String uploadHtmlFile(String fileName, InputStream inputStream) throws IOException, ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
//       文件名处理
        fileName = UUID.randomUUID() + fileName;
//        文件上传操作
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(minioConfigerProperties.getBucket())
                .object(fileName)
                .contentType("text/html")
                .stream(inputStream, inputStream.available(), -1)
                .build();
        ObjectWriteResponse response = minioClient.putObject(putObjectArgs);
//        url
        String objectUrl = minioClient.getObjectUrl(putObjectArgs.bucket(), putObjectArgs.object());
        return objectUrl;
    }

    @Override
    public String uploadImageFile(String fileName, InputStream inputStream) throws IOException, ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
//       文件名处理
        fileName = UUID.randomUUID() + fileName;
//        文件上传操作
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(minioConfigerProperties.getBucket())
                .object(fileName)
                .contentType("image/jpg")
                .stream(inputStream, inputStream.available(), -1)
                .build();
        ObjectWriteResponse response = minioClient.putObject(putObjectArgs);
//        url
        String objectUrl = minioClient.getObjectUrl(putObjectArgs.bucket(), putObjectArgs.object());
        return objectUrl;
    }
}
